use crate::global_context::GlobalContext;
use serde::Deserialize;
use std::sync::Mutex;
use tauri::State;
use tauri_plugin_opener::OpenerExt;

#[tauri::command]
pub fn open_path(uri: String, app: tauri::AppHandle) {
    app.opener().open_path(uri, None::<&str>).unwrap();
}

#[derive(Deserialize)]
pub struct WindowStateParam {
    label: String,
    url: String,
    width: f64,
    height: f64,
    title: String,
}

#[tauri::command]
pub fn create_window(
    app: tauri::AppHandle,
    config: WindowStateParam,
    state: State<'_, Mutex<GlobalContext>>,
) {
    let mut state = state.lock().unwrap();
    let mut idx: usize = 0;
    for win in &state.win_array {
        // 如果存在相同label的窗口
        if win.label() == config.label {
            // 获取可视状态
            let vis = win.is_visible();
            if !vis.is_err() && vis.unwrap() {
                // 如果窗口已关闭，则会is_err
                // 已显示时，直接让窗口获取焦点
                win.set_focus().expect("Fail to set focus");
                return;
            }
            // 已关闭时，直接destroy，并从state中移除该窗口
            win.destroy().expect("Fail to destory");
            state.win_array.remove(idx);
            break;
        }
        idx += 1;
    }
    let w_builder = tauri::WebviewWindowBuilder::new(
        &app,
        config.label,
        tauri::WebviewUrl::App(config.url.into()),
    )
    .inner_size(config.width, config.height)
    .title(config.title);
    #[cfg(target_os = "macos")]
    let w_builder = w_builder.title_bar_style(tauri::TitleBarStyle::Transparent);
    #[cfg(target_os = "windows")]
    let w_builder = w_builder.title_bar_style(TitleBarStyle::Overlay);
    let webview_window = w_builder.build().unwrap();
    state.win_array.push(webview_window);
}
